package com.yq.day30;


import java.util.Random;

/**
 * @author 3307235355@qq.com
 * @description
 * @since 2022/06/30 09:25
 */
public class Demo01 {
    public static void main(String[] args) {
        Box box = new Box();
        ProducerTask p1 = new ProducerTask(box);
        ConsumerTask c1 = new ConsumerTask(box);

        new Thread(p1).start();
        new Thread(c1).start();

    }
}

class Box {
    Food food;

    //    吃
    public synchronized void setFood(Food newFood) {
        if (food==null){
            food=newFood;
            System.out.println("create box");
            this.notify();
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    //    生产
    public synchronized void eatFood() {
        if (food==null){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("eating");
            food=null;
            this.notify();
        }
    }

}


class Food {
    String name;
    int price;

    @Override
    public String toString() {
        return "Food{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public Food(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

class ProducerTask implements Runnable{

    Box box;
    Food[] foods ={new Food("1",12),
    new Food("2",13),
    new Food("23",14)};
    Random random = new Random();

    public ProducerTask(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        //只生产
        while(true){
            box.setFood(foods[random.nextInt(foods.length)]);
        }

    }
}


class ConsumerTask implements Runnable{
    Box box;

    public ConsumerTask(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            box.eatFood();
        }
    }
}